package com.task.mall.controller.admin;

import com.google.gson.*;
import com.task.mall.bean.Goods;
import com.task.mall.bean.Result;
import com.task.mall.bean.Spec;
import com.task.mall.service.GoodsService;
import com.task.mall.service.impl.GoodsServiceImpl;
import com.task.mall.utils.FileUploadUtils;
import com.task.mall.utils.HttpUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/api/admin/goods/*")
public class GoodsServlet extends HttpServlet {
    GoodsService goodsService = new GoodsServiceImpl();
    Gson gson = new Gson();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String action = requestURI.replace("/api/admin/goods/", "");
        if ("imgUpload".equals(action)){
            imgUpload(request,response);
        }else if ("addGoods".equals(action)){
            addGoods(request,response);
        }else if ("updateGoods".equals(action)){
            updateGoods(request,response);
        }else if ("addSpec".equals(action)){
            addSpec(request,response);
        }else if ("deleteSpec".equals(action)){
            deleteSpec(request,response);
        }
    }

    /**
     * 删除规格
     * @param request
     * @param response
     */
    private void deleteSpec(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        Spec spec = gson.fromJson(requestBody, Spec.class);
        int result = goodsService.deleteSpec(spec);
        Result res = new Result();
        if (result == 200){
            res.setCode(0);
            res.setData(spec);
        }
        response.getWriter().println(gson.toJson(res));
    }

    /**
     * 添加规格（尺码及其库存和价格）
     * @param request
     * @param response
     */
    private void addSpec(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        Spec spec = gson.fromJson(requestBody, Spec.class);
        int result = goodsService.addSpec(spec);
        Result res = new Result();
        if (result == 200){
            res.setCode(0);
            res.setData(spec);
        }
        response.getWriter().println(gson.toJson(res));
    }

    /**
     * 更新商品相关信息（描述，尺码及其库存和价格）
     * @param request
     * @param response
     */
    private void updateGoods(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        Goods goods = gson.fromJson(requestBody, Goods.class);
        int result = goodsService.updateGoods(goods);
        Result res = new Result();
        if (result == 200){
            res.setCode(0);
        }
        response.getWriter().println(gson.toJson(res));
    }

    /**
     * 上架商品，并添加具体信息（描述，尺码及其库存和价格）
     * @param request
     * @param response
     */
    private void addGoods(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        Goods goods = gson.fromJson(requestBody, Goods.class);
        // 法子2 -- 百分百获取到goods对象
        // JsonElement jsonElement = new JsonParser().parse(requestBody);
        // JsonObject jsonObject = jsonElement.getAsJsonObject();
        // JsonArray specList = jsonObject.getAsJsonArray("specList");
        // jsonElement -- jsonObject -- specList(for遍历出所需要的对象)
        // for (JsonElement element : specList) {
        //     Spec spec = gson.fromJson(element, Spec.class);
        //     System.out.println(spec);
        // }
        // 保存goods spec
        int result = goodsService.addGoods(goods);
        Result res = new Result();
        if (result == 200){
            res.setCode(0);
        }
        response.getWriter().println(gson.toJson(res));
    }

    /**
     * 上传商品的图片具体代码逻辑 -- 切记是和form表单分开的
     * 先传图片地址，再将地址返回后，进行表单上传
     * @param request
     * @param response
     */
    private void imgUpload(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 输出的既是配置文件中的内容：localhost：8084
        String domain = (String) request.getServletContext().getAttribute("domain");
        Map<String, Object> map = FileUploadUtils.parseRequest(request);
        Result res = new Result();
        res.setCode(0);
        // 拼接完成整的图片地址 -- localhost:8084/upload/......jpeg
        res.setData(domain + map.get("file"));
        response.getWriter().println(gson.toJson(res));
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String action = requestURI.replace("/api/admin/goods/", "");
        if ("getGoodsByType".equals(action)){
            getGoodsByType(request,response);
        }else if ("getGoodsInfo".equals(action)){
            getGoodsInfo(request,response);
        }else if("deleteGoods".equals(action)){
            deleteGoods(request,response);
        }
    }

    /**
     * 下架商品
     * @param request
     * @param response
     */
    private void deleteGoods(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        int result = goodsService.deleteGoods(id);
        Result res = new Result();
        if (result == 200){
            res.setCode(0);
        }
        response.getWriter().println(gson.toJson(res));
    }

    /**
     * 获取具体商品信息（描述，图片存储路径，规格及其库存）
     * @param request
     * @param response
     */
    private void getGoodsInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        Goods goods = goodsService.getGoodsInfo(id);
        List<Spec> specList = goodsService.getGoodSpecListInfo(id);
        Map<String,Object> map = new HashMap<>(2);
        map.put("specs",specList);
        map.put("goods",goods);
        Result res = new Result();
        res.setCode(0);
        res.setData(map);
        response.getWriter().println(gson.toJson(res));
    }

    /**
     * 获取某个商品类目下所有商品的逻辑
     * @param request
     * @param response
     */
    private void getGoodsByType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String typeId = request.getParameter("typeId");
        List<Goods> goodsList = goodsService.getGoodsByType(typeId);
        Result res = new Result();
        res.setCode(0);
        res.setData(goodsList);
        response.getWriter().println(gson.toJson(res));
    }
}
